//
// Created by 崔世强 on 2018/3/29.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON
import Toast_Swift
import SnapKit

fileprivate enum Mode {
    case Look
    case Edit
}

class ModifyGroupAnnouncementController:ChatBaseController {
    
    
    fileprivate var mode = PropertyObservable<Mode>()
    
    lazy var doneButtonItem: UIBarButtonItem = {
        let barItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(editDone))
        barItem.isEnabled = false
        return barItem
    }()
    
    var groupId:Int!
    var announcement:String?
    let service = GroupService()
    let msgService = ChatService()
    
    lazy var textView:UITextView = {
        let view = UITextView()
        view.textAlignment = .left
        view.font = UIFont.systemFont(ofSize: 16.0)
        view.isScrollEnabled = true
        view.isEditable = true
        view.isSelectable = true
        view.delegate = self
        return view
    }()
    
    lazy var tableView: UITableView = {
        var table = UITableView(frame: self.view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        //        table.backgroundColor = .clear
        table.estimatedRowHeight = 200
        table.rowHeight = 150
        return table
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(tableView)
        self.navigationItem.rightBarButtonItem = doneButtonItem
    }
    
}
extension ModifyGroupAnnouncementController {
    fileprivate func onSuccess() {
        DispatchQueue.main.async {
            self.view.hideToastActivity()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    fileprivate func onFailure(_ msg:String) {
        DispatchQueue.main.async {
            self.view.hideToastActivity()
            self.view.makeToast(msg, position: .center)
        }
    }
    
    @objc func editDone() {
        self.view.makeToastActivity(.center)
        self.announcement = textView.text
        let userId = AppStatusManager.instance.userLoginStatus.1 ?? 0
        IM.request(.modifyGroupAnnouncement(groupId: groupId, userId: userId, announcement: self.announcement ?? ""),success: { [unowned self] (json) in
            if reqSuccess(json["code"].stringValue) {
                do {
                    try self.service.update(self.groupId, withAnnouncement: self.announcement ?? "")
                } catch {
                    print(error)
                }
                let dic:[String:Any] = ["type":NoticeType.modifyGroupAnnouncement.rawValue,"announcement":self.announcement ?? ""]
                let msgJson = JSON(dic)
                self.msgService.sendNoticeMsg(msgJson.rawString() ?? "", to: self.groupId, chatType: .group)
                self.onSuccess()
            } else {
                let msg = json["msg"].stringValue
                self.onFailure(msg)
            }
            }, error: { (code) in
                print("状态异常：\(code)")
                self.onFailure("服务异常，请稍后再试")
        }) { (error) in
            print(error)
            self.onFailure("服务或网络异常")
        }
    }
}

extension ModifyGroupAnnouncementController:UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        self.doneButtonItem.isEnabled = true
        return true
    }
    
    func textViewDidChange(_ textView: UITextView) {  //群公告限制最大输入字数500字
        let maxLength = 500
        let text = textView.text ?? ""
        if let selectedRange = textView.markedTextRange, let position = textView.position(from: selectedRange.start, offset: 0) {} else {
            if text.count > maxLength {
                textView.text = text.substring(s: 0, maxLength)
            }
        }
    }
    
}


extension ModifyGroupAnnouncementController: UITableViewDelegate, UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    //生成表视图单元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "TextField"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
        }
        cell?.contentView.addSubview(textView)
        
        textView.snp.makeConstraints{ make in
            make.edges.equalToSuperview()
        }
        textView.text = self.announcement
        return cell!
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "群公告"
    }
    
    //获取分组数量
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
}
